package com.rslai.commons.http.methods;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BufferedHeader;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.CharArrayBuffer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;

/**
 * 包装的 post 方法
 * Created by lrs on 2018/8/6.
 */
public class RslaiHttpPost extends HttpPost {

    private final Log log = LogFactory.getLog(getClass());

    /**
     * 默认构造方法
     */
    public RslaiHttpPost() {
        super();
    }

    /**
     * 使用 URI 构造
     * @param uri uri 字符串
     */
    public RslaiHttpPost(final URI uri) {
        super(uri);
    }

    /**
     * 使用字符串 uri 地址构造
     * @param uri uri
     * @throws IllegalArgumentException 如果 uri 无效抛出此异常
     */
    public RslaiHttpPost(final String uri) {
        super(uri);
    }

    /**
     * 设置 header 头
     * @param headers header字符串
     * @throws ParseException ParseException
     * @throws IOException IOException
     */
    public void addHeader(String headers) throws ParseException, IOException {
        BufferedReader bufferedReader = new BufferedReader(new StringReader(headers));
        String line = null;

        while ((line = bufferedReader.readLine()) != null) {
            CharArrayBuffer buffer = new CharArrayBuffer(30);
            buffer.clear();
            buffer.append(line);
            this.addHeader(new BufferedHeader(buffer));
        }

    }

    /**
     * 设置 UA
     * @param userAgent userAgent
     */
    public void setUserAgent(String userAgent) {
        this.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgent);
    }

}
